<template>
  <div>
<!--    面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    卡片区域-->
<!--    分栏-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入查找内容"
                    v-model="paramsInfo.query"
                    clearable
                    @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
<!--      index代表索引列 border表格边框 stripe隔行变色-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username">

        </el-table-column>
        <el-table-column label="邮箱" prop="email">

        </el-table-column>
        <el-table-column label="电话" prop="mobile">

        </el-table-column>
        <el-table-column label="角色" prop="role_name">

        </el-table-column>
<!--        作用域插槽会覆盖prop，故prop可省略-->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">

            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
<!--          修改按钮-->
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="updateUser(scope.row.id)"></el-button>
<!--          删除按钮-->
          <el-button type="danger" icon="el-icon-delete" size="mini"
          @click="deleteUserById(scope.row.id)"></el-button>

          <el-tooltip effect="dark" placement="top" content="分配角色" :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
          </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="paramsInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="paramsInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
<!--      添加用户的对话框-->
      <el-dialog title="添加用户"
                 :visible.sync="addDialogVisible"
                  width="50%"
                  @close="addDialogClosed">
<!--      内容主题区域-->
        <el-form
            ref="addUserFormRef"
            :rules="addUserFormRules"
            :model="addUserForm" label-width="70px" class="addUser_form">
          <!--      用户名-->
          <el-form-item label="用户名" prop="username">
            <el-input  v-model="addUserForm.username">
            </el-input>
          </el-form-item>
          <!--      密码-->
          <el-form-item label="密码" prop="password">
            <el-input
                v-model="addUserForm.password"
                type="password">
            </el-input>
          </el-form-item>
<!--          邮箱-->
          <el-form-item label="邮箱" prop="email">
            <el-input
                v-model="addUserForm.email">
            </el-input>
          </el-form-item>
<!--          电话-->
          <el-form-item label="电话" prop="mobile">
            <el-input
                v-model="addUserForm.mobile">
            </el-input>
          </el-form-item>
        </el-form>
<!--        底部区域-->
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible=false">取消</el-button>
            <el-button type="primary" @click="addUser">确定</el-button>
          </span>
      </el-dialog>
<!--      -------------!!!!!!!!!!!!!!!!!!!!!!-->
<!--      修改用户信息对话框-->
      <el-dialog title="修改用户信息"
                 :visible.sync="updateDialogVisible"
                 width="50%"
                 @close="updateDialogClosed">
        <!--      内容主题区域-->
      <el-form
          ref="editFormRef"
          :rules="editFormRules"
          :model="editForm" label-width="70px">
        <!--      用户名-->
        <el-form-item label="用户名" prop="username">
          <el-input  v-model="editForm.username" disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input  v-model="editForm.email">
          </el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input  v-model="editForm.mobile">
          </el-input>
        </el-form-item>
      </el-form>
      <!--        底部区域-->
      <span slot="footer">
            <el-button @click="updateDialogVisible=false">取消</el-button>
            <el-button type="primary" @click="editUser">确定</el-button>
          </span>
      </el-dialog>

    </el-card>

  </div>
</template>

<script>
export default {
  name: "User",
  data(){
    //自定义手机号验证规则
    let checkMobile = (rule,value,cb)=>{
        const regMobile =  /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if(regMobile.test(value))
    //      如果合法
          return cb()
      cb(new Error('请输入合法的手机号'))
    }
    return {
      //添加用户表单
      addUserForm:{
        username: '',
        password: '',
        email:'',
        mobile:'',
      },
      //用户表单校验规则
      addUserFormRules:{
        username:[
          {required:true,message:'请输入用户名',trigger:'blur'},
          {min:3,max:8,message: '长度在 3到8个字符',trigger:'blur'}
        ],
        password: [
          {required:true,message:'请输入密码',trigger:'blur'},
          {min:6,max:12,message: '长度在 6到12个字符',trigger:'blur'}
        ],
        email:[
          {required:true,type:'email',message:'请输入正确的邮箱地址',trigger:['blur','change']},
        ],
        mobile: [
          {required:true,message:'请输入电话号码',trigger:'blur'},
          {validator:checkMobile,trigger: 'blur'},
        ]
      },
      //是否显示更新用户对话框
      updateDialogVisible:false,
      //是否显示添加用户提示框
      addDialogVisible:false,
      // 请求 保存get请求的params参数
      //对象中的key名必须与服务器提供的一致！！！！！！！！
      paramsInfo:{
        //查询关键字
        query:'',
        //当前页码
        pagenum:1,
        pagesize:2,
      },
      //响应 保存接受的数据
      userList:[],
      total:0,
      //保存查询到的用户信息
      editForm:{},
      editFormRules:{
        email:[
          {required:true,type:'email',message:'请输入正确的邮箱地址',trigger:['blur','change']},
        ],
        mobile: [
          {required:true,message:'请输入电话号码',trigger:'blur'},
          {validator:checkMobile,trigger: 'blur'},
        ]
      },
    }
  },
  created(){
    this.getUserList()
  },
  methods:{
    async getUserList(){
      const {data:result} = await this.$axios.get(
          'users',
          {params:this.paramsInfo})
      console.log(result)
      if(result.meta.status !== 200)
        return this.$message.error('获取用户列表失败')
      this.userList = result.data.users
      this.total = result.data.total
    },
    //监听页面大小改变
    handleSizeChange(pagesize){
        this.paramsInfo.pagesize = pagesize
        this.getUserList()
    },
    //监听页面页码改变
    handleCurrentChange(pagenum){
      this.paramsInfo.pagenum = pagenum
      //需要重新获取列表！！！
      this.getUserList()
    },
    async userStateChanged(userInfo){
      const {data:res} =await this.$axios.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if(res.meta.status !== 200){
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      return  this.$message.success(('更新用户状态成功'))
    },
    //重置表单
    addDialogClosed(){
      this.$refs.addUserFormRef.resetFields()
    },
  //  添加用户
    addUser(){
      this.$refs.addUserFormRef.validate(async valid=>{
        if(!valid) return
      //  发起添加用户的网络请求
        const {data:res} = await this.$axios.post('users',this.addUserForm)
        if(res.meta.status !==201)
          this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        //隐藏对话框
        this.addDialogVisible=false
        //重新请求用户列表
        this.getUserList()
      })
    },
    async updateUser(id){
        let {data:res} = await this.$axios.get('users/'+id)
        if(res.meta.status !== 200)
            return this.$message.error('查询用户信息失败')
        this.editForm = res.data
        this.updateDialogVisible = true
    },
    updateDialogClosed(){
        this.$refs.editFormRef.resetFields()
    },
    //修改用户信息
    editUser(){
      this.$refs.editFormRef.validate(async valid=>{
        if(!valid) return
        //  发起添加用户的网络请求
        const {data:res} = await this.$axios.put('users/'+this.editForm.id,{
          email:this.editForm.email,
          mobile:this.editForm.mobile,
        })
        if(res.meta.status !==200)
          this.$message.error('更新用户失败')
        this.$message.success('更新用户成功')
        //隐藏对话框
        this.updateDialogVisible=false
        //重新请求用户列表
        this.getUserList()
      })
    },
    async deleteUserById(id){
      const result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data:res} = await this.$axios.delete('users/'+id)
        if(res.meta.status !== 200)
          this.$message.error('删除用户失败')
        this.$message({
          type: 'success',
          message: '删除用户成功!'
        });
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
  },
}
</script>

<style scoped>

</style>